My java program seems to be skipping over the try{}, executing the catch{} and then throwing a NullPointerException. What should I do?

Posted by Matt Bolopue on Stack Overflow See other posts from Stack Overflow or by Matt Bolopue
Published on 2012-11-03T04:18:50Z Indexed on 2012/11/03 5:01 UTC
Read the original article Hit count: 173

Filed under:
|
|

I am writing a program that calculates the number of words, syllables, and sentences in any given text file. I don't need help finding those numbers, however my program (which currently should only find the number of words in the text file) will not import the text file even when I type in the name of the file correctly. The text file is in the same folder as the source code. Instead it tells me every time that what I typed in has the wrong file extension (see my catch{}) and then proceeds to throw a null pointer. I am at a loss for what could be causing it. Any suggestions?

import java.io.*;
import java.util.*;

public class Reading_Lvl_Calc {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int words = 0;
        String fileName;
        Scanner scan;
        Scanner keyread = new Scanner(System.in);
        System.out.println("Please enter a file name (or QUIT to exit)");
        fileName = keyread.nextLine();
        File doc = new File(fileName);
        //while(scan.equals(null)){
        try
        {   
            scan = new Scanner(doc);
        }
        catch(Exception e)
        {   
            if(fileName.substring(fileName.indexOf(".")) != ".txt")
            System.out.println("I'm sorry, the file \"" + fileName + "\" has an invalid file extension.");
            else 
            System.out.println("I am sorry, the file \"" + fileName + " \" cannot be found.\n The file must be in the same directory as this program");
            scan = null;
        }
    //  }
        while(scan.hasNext()){
            words++;
            scan.next();
        }
        System.out.println(words);

    }

}

© Stack Overflow or respective owner

Related posts about java

Related posts about null